package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 统计区间段的每日营业额统计
     * @param begin 开始日期
     * @param end 结束日期
     * @return 返回TurnoverReportVO对象
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //1.用集合存放从begin到end的所有日期
        List<LocalDate> dates = new ArrayList<>();
        dates.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dates.add(begin);
        }
        //2.查询出每个日期对应的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dates) {
            //只统计已完成下单的金额，status = 5
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            map.put("status", Orders.COMPLETED);
            Double d = orderMapper.sumByMap(map)==null? 0.0:orderMapper.sumByMap(map);//返回数据统计总额,没有数据时返回的是null，
            turnoverList.add(d);
            //select sum(amount) from orders where status = 5 and order_time >? and order_time<?
            // between "date1" and "date2"
        }

        return TurnoverReportVO.builder().
                dateList( StringUtils.join(dates,",")).turnoverList(StringUtils.join(turnoverList)).
                build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //1.用集合存放从begin到end的所有日期
        List<LocalDate> dates = new ArrayList<>();
        dates.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dates.add(begin);
        }
        //存放每天用户新增数量
        List<Integer> newUserList = new ArrayList<>();
        //存放每天用户总数
        List<Integer> totalList = new ArrayList<>();
        for (LocalDate date : dates) {
            //计算每天新增用户数量
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("endTime",endTime);

            totalList.add(userMapper.countByMap(map)) ;//获取当日的用户总数
            map.put("beginTime",beginTime);
            newUserList.add(userMapper.countByMap(map));//计算每天新增用户总数
        }
        return UserReportVO.builder().dateList(StringUtils.join(dates,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalList,",")).build();
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //1.用集合存放从begin到end的所有日期
        List<LocalDate> dates = new ArrayList<>();
        dates.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dates.add(begin);
        }
        //2.每日订单数
        List<Integer> orderCountList = new ArrayList<>();
        //3.每日有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dates) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //计算每天订单数量
            Integer orderCount = getOrderSum(beginTime,endTime,null);
            //计算每天有效订单数量，即已完成付款且派送的
            Integer validOrder = getOrderSum(beginTime,endTime,Orders.COMPLETED);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrder);
        }
        //4.区间内订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //5.区间有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //6.订单完成率，订单总数可能为0要注意异常
        Double orderCompletionRate = 0.0;
        if (totalOrderCount!=0){
            orderCompletionRate = validOrderCount.doubleValue()/totalOrderCount;
        }

        return OrderReportVO.builder().dateList(StringUtils.join(dates,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);//LocalDate+LocalTime,合编成LocalDateTime
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        //返回的是个对象集合，使用stream流处理
        //商品名称列表
        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameLists = StringUtils.join(nameList, ",");
        //销量列表
        List<Integer> numList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numbers = StringUtils.join(numList, ",");

        return SalesTop10ReportVO.builder().numberList(numbers).nameList(nameLists).build();
    }

    private Integer getOrderSum(LocalDateTime beginTime,LocalDateTime endTime,Integer status){
        Map map = new HashMap();
        map.put("beginTime",beginTime);
        map.put("endTime",endTime);
        map.put("status",status);
        return orderMapper.countByMap(map);
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {//获取近30天的数据
        //1.获取营业数据，定义端点日期值
        LocalDate start = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);//不能获取今天的营业数据

        //查询概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(start, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        //2. 通过POI将数据写入到Excel文件中
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try (XSSFWorkbook excel = new XSSFWorkbook(is);//基于模板文件创建一个新的Excel文件
             ServletOutputStream out = response.getOutputStream();
        ) {
            XSSFSheet sheet1 = excel.getSheet("Sheet1");//获取表格文件的Sheet页
            //填充数据--时间
            sheet1.getRow(1).getCell(1).setCellValue("时间：" + start + "至" + end);
            //填充概览数据
            //获取第4行
            XSSFRow row = sheet1.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            //获得第5行
            row = sheet1.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            //填充明细数据 30行，每日的营业数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = start.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet1.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData1.getTurnover());
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                row.getCell(6).setCellValue(businessData1.getNewUsers());
            }
            excel.write(out);//3. 通过输出流将Excel文件下载到客户端浏览器
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
